package com.dynamicthreadpool.factory;

import com.dynamicthreadpool.spi.ExtensionLoader;
import com.dynamicthreadpool.spi.DynamicThreadFactory;
import com.dynamicthreadpool.spi.URL;

import java.util.concurrent.ThreadFactory;

/**
 * 线程工厂工厂，基于SPI机制加载线程工厂实现
 */
public final class ThreadFactoryFactory {

    private static final ExtensionLoader<DynamicThreadFactory> EXTENSION_LOADER = ExtensionLoader.getExtensionLoader(DynamicThreadFactory.class);

    /**
     * 获取线程工厂
     *
     * @param name 线程工厂名称
     * @return 线程工厂实例
     */
    public static DynamicThreadFactory getThreadFactory(String name) {
        DynamicThreadFactory factory = EXTENSION_LOADER.getExtension(name != null && !name.isEmpty() ? name : "named");
        return factory;
    }
    
    /**
     * 根据URL获取线程工厂
     *
     * @param url URL对象，包含线程池配置信息
     * @param defaultName 默认线程池名称
     * @return 线程工厂实例
     */
    public static DynamicThreadFactory getThreadFactory(URL url, String defaultName) {
        String factoryName = url.getParameter("threadfactory", "named");
        String threadName = url.getParameter("threadname", defaultName);
        boolean daemon = url.getParameter("daemon", false);
        
        DynamicThreadFactory factory = getThreadFactory(factoryName);
        return factory.setName(threadName).setDaemon(daemon);
    }
}